package com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter

import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.app.Xutils
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdRequestParams
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.PvUvRetrofit
import com.kanshu.ksgb.fastread.doudou.common.net.rx.NothingObserverUtils
import com.ss.android.common.lib.AppLogNewUtils
import com.umeng.analytics.MobclickAgent
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import org.json.JSONObject
import kotlin.math.min

/**
 * Title:AdPresenter.kt
 * Description:
 * Copyright: Copyright(c)2018
 * Company: 看书网
 * CreateTime: 2018/6/5 9:58
 *
 * @author EvanHe
 * @version 3.0
 */
class AdPresenter {

    companion object {
        const val AD_REQUEST = "ad_request"
        const val AD_SHOW = "ad_show"
        const val AD_CLICK = "ad_click"
        /**
         * 上报PVUV广告统计
         *
         * @param pVUVType 请求:ad_request 曝光:ad_show  点击:ad_click
         * @param adType 广告商
         * @param adPos 广告位置
         */
        @JvmStatic
        fun pVUVAdStatics(pVUVType: String, adType: String, adPos: Int) {
            val param = AdRequestParams()
            param.pv_uv_page_type = pVUVType
            param.ad_type = adType
            param.ad_position = adPos.toString()
            PvUvRetrofit.getInstance().create(AdService::class.java)
                    .pVUVAdStatics(param)
                    .subscribe(object : Observer<BaseResult<String>> {
                        override fun onSubscribe(d: Disposable) {
                        }

                        override fun onNext(stringBaseResult: BaseResult<String>) {
                        }

                        override fun onError(e: Throwable) {
                            e.printStackTrace()
                        }

                        override fun onComplete() {
                        }
                    })
        }

        @JvmStatic
        fun pvuvStatics(pvuvType: String, bookId: String?) {

            val params = mutableMapOf<String, String?>()
            params["pv_uv_page_type"] = pvuvType
            params["book_id"] = bookId
            PvUvRetrofit.getInstance().create(AdService::class.java)
                    .pVUVstatics(params)
                    .subscribe(NothingObserverUtils.nothingObserver)
        }

        /**
         * 埋点统计（包括我们后台和友盟的统计）
         * @param pvuvType 字符串资源id
         */
        @JvmStatic
        fun pvuvStatics(pvuvType: Int) {
            pvuvStaticsByString(Xutils.getContext().getString(pvuvType))
        }

        @JvmStatic
        fun pvuvStatics(pos: Int, vararg ids: Int) {
            val id = ids.getOrNull(pos) ?: return
            pvuvStatics(id)
        }

        /**
         * @param bean 有广告的列表
         * @param isAd 检查是否是广告 是广告返回true
         */
        @JvmStatic
        fun <T> pvuvStatics(bean: List<T>?, isAd: (T) -> Boolean, pos: Int, vararg ids: Int) {

            if (bean?.isNotEmpty() == true) {
                val index = min(pos + 1, bean.size)
                var pos2 = pos
                for (i in 0 until index) {
                    if (isAd(bean[i])) {
                        pos2--
                    }
                }
                pvuvStatics(pos2, *ids)
            } else {
                pvuvStatics(pos, *ids)
            }

        }

        /**
         * 书籍搜索上报
         */
        @JvmStatic
        fun pvuvStaticsSearch(key: String) {
            val type = "SCSEARCH"
            //baseUrl 不同
            PvUvRetrofit.getInstance()
                    .create(AdService::class.java)
                    .pVUVstaticsSearch(type = type, keyword = key)
                    .subscribe(NothingObserverUtils.nothingObserver)
            // Umeng统计
            MobclickAgent.onEvent(Xutils.getContext(), Xutils.getContext().getString(R.string.statistics_prefix) + type)
        }

        @JvmStatic
        fun pvuvStaticsByString(pvuvType: String) {

            val list = pvuvType.split("&")
            val params = HashMap<String, String>(list.size)
            params["pv_uv_page_type"] = list[0]
            for (i in 1 until list.size) {
                val split = list[i].split("=")
                if (split.size == 2)
                    params[split[0]] = split[1]
            }
            PvUvRetrofit.getInstance()
                    .createService(AdService::class.java)
                    .pVUVstatics(params)
                    .subscribe(NothingObserverUtils.nothingObserver)
            // Umeng统计
            MobclickAgent.onEvent(Xutils.getContext(), Xutils.getContext().getString(R.string.statistics_prefix) + list[0])

        }

        /**
         * 头条相关的类 [com.ss.android.common.applog.TeaAgent],[com.ss.android.common.lib.EventUtils],[com.ss.android.common.lib.AppLogNewUtils]
         *
         * 头条上报自定义事件。
         * @param anys 成对的参数。例如：[key,value,key,value]  key必须为字符串
         */
        @JvmStatic
        fun touTiaoEvent(type: Int, vararg kvs: Any) {
            //也许需要添加一些公告参数。暂时没有需求
            val json = JSONObject()
            for (i in 1 until kvs.size step 2) {
                json.put(kvs[i - 1].toString(), kvs[i])
            }

            val string = Xutils.getContext().resources.getString(type)
            AppLogNewUtils.onEventV3(string, json)
        }


    }
}